package org.example.infrastructure.event;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import org.example.types.event.BaseEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息发送工具包,定义相关消息队列 发送消息的方法
 */
@Slf4j
@Component
public class EventPublisher {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 将消息转换为json再发送出去
     * @param topic 待消息主题
     * @param eventMessage 消息实体
     */
    public void publish(String topic, BaseEvent.EventMessage<?> eventMessage) {
        try {
            String messageJson = JSON.toJSONString(eventMessage);
            rocketMQTemplate.convertAndSend(topic, messageJson);
            log.info("发送MQ消息 topic:{} message:{}", topic, messageJson);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topi c:{} message:{}", topic, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }

    /**
     * 直接发送转换为json后的消息
     * @param topic 待发送消息主题
     * @param eventMessageJSON 消息实体的json格式
     */
    public void publish(String topic, String eventMessageJSON){
        try {
            rocketMQTemplate.convertAndSend(topic, eventMessageJSON);
            log.info("发送MQ消息 topic:{} message:{}", topic, eventMessageJSON);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic:{} message:{}", topic, eventMessageJSON, e);
            throw e;
        }
    }

}
